﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.Windows.Controls;
using System.ComponentModel;
using System.Windows.Data;
using System.Windows.Markup;

namespace Tanmia.Basis.WPF.Controls
{
    public class GridBinding : ExtendedMarkupExtension
    {
        private DataGrid grid;
        private Binding innerBinding;

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            IProvideValueTarget provideValueTarget = GetService<IProvideValueTarget>(serviceProvider);

            if (provideValueTarget != null)
            {
                this.grid = provideValueTarget.TargetObject as DataGrid;
                this.grid.AutoGeneratingColumn += new EventHandler<DataGridAutoGeneratingColumnEventArgs>(grid_AutoGeneratingColumn);
            }

            innerBinding = new Binding();
            innerBinding.Path = Path;
            object obj = innerBinding.ProvideValue(serviceProvider);
            return obj;
        }

        private void grid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            DisplayAttribute displayAtt = GetCustomAttribute<DisplayAttribute>(e.PropertyDescriptor as PropertyDescriptor);

            if (displayAtt != null)
            {
                e.Column.Header = displayAtt.ShortName;
                //e.Column.DisplayIndex = displayAtt.Order;
            }
            else
                e.Cancel = true;
        }


    }
}
